﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BSCMFF.Core.DataAccessLayer;
using BSCMFF.Web.UserControls;
using Telerik.Web.UI;
using BSCMFF.Core.Exceptions.Database;

namespace BSCMFF.Web.Pages.Evaluation_Setup.Personalist
{
    /// <summary>
    /// Create or edit evaluation period.
    /// </summary>
    /// <remarks></remarks>
    public partial class EvaluationEditMode : BSCMFF.Core.MultiLanguagePage
    {
        /// <summary>
        /// number of categories for evaluating general KPIs
        /// </summary>
        private static int categories = 0;

        /// <summary>
        /// Gets the categories.
        /// </summary>
        /// <remarks></remarks>
        public int Categories 
        { 
            get
            {
                return categories;
            }
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["EvaluationID"] != null)
                {
                    int evalID = Convert.ToInt32(Request.QueryString["EvaluationID"]);


                    BSCEntities context = new BSCEntities();
                    Evaluation_Period selectedEval = (from ev in context.Evaluation_Period
                                                      where ev.ID == evalID
                                                      select ev).SingleOrDefault();
                    ed.Evalut = selectedEval;
                    ed.DataBind();

                    LoadCategories(evalID);

                    CheckBoxPKPIs.Checked = selectedEval.PKPIs.Value;
                    CheckBoxCompetencies.Checked = selectedEval.Competencies.Value;
                    CheckBoxReward.Checked = selectedEval.Reward.Value;
                    RadButtonCreateTypes_Click(sender, e);
                    LoadEvalProperties(selectedEval);
                    //LoadUsers(evalID);

                    RadButtonCancel.Text = "Back";
                    RadButtonDelete.Visible = true;
                }
                else
                {
                    CreateCategory2(); //RadButtonAddCategory_Click(sender, new EventArgs());
                    RadButtonDelete.Visible = false;
                    //categories = 1;
                }
                RadButtonSave.Visible = true;                
            }
        }
        
        /// <summary>
        /// Handles the Click event of the RadButtonCreateTypes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void RadButtonCreateTypes_Click(object sender, EventArgs e)
        {
            PlaceHolderParts.Visible = true;
            PlaceHolderInterviewPart.Visible = true;

            if (CheckBoxReward.Checked && !CheckBoxPKPIs.Checked && !CheckBoxCompetencies.Checked)
            {
                LabelRewardWarning.Visible = true;
                return;
            }
            LabelRewardWarning.Visible = false;
            PlaceHolderPKPIsPart.Visible = CheckBoxPKPIs.Checked;
            PlaceHolderCompetenciesPart.Visible = CheckBoxCompetencies.Checked;
            PanelRewardCompetenciesSetting.Visible = CheckBoxCompetencies.Checked;
            PlaceHolderRewardPart.Visible = CheckBoxReward.Checked;
                        
            RadButtonCreateTypes.Text = "Update";            
        }

        /// <summary>
        /// Handles the Click event of the RadButtonAddCategory control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void RadButtonAddCategory_Click(object sender, EventArgs e)
        {
            CreateCategory2();

            CreateCategoryButtonVisibility();

            DeleteCategoryButtonVisibility();
        }

        /// <summary>
        /// Creates the category button visibility.
        /// </summary>
        /// <remarks></remarks>
        private void CreateCategoryButtonVisibility()
        {
            if (categories >= 9)
            {
                RadButtonSave.Visible = false;
            }
            else
            {
                RadButtonSave.Visible = true;
            }
        }

        /// <summary>
        /// Handles the Click event of the RadButtonDeleteCategory control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void RadButtonDeleteCategory_Click(object sender, EventArgs e)
        {
            EvaluationQuestionCategory eqc = (EvaluationQuestionCategory)PlaceHolderCategories.FindControl("EvaluationQuestionCategory" + (--categories).ToString());
            eqc.Visible = false;
            eqc.EnableViewState = false;

            DeleteCategoryButtonVisibility();
        }

        /// <summary>
        /// Deletes the category button visibility.
        /// </summary>
        /// <remarks></remarks>
        private void DeleteCategoryButtonVisibility()
        {
            if (categories <= 0)
            {
                RadButtonDeleteCategory.Visible = false;
            }
            else
            {
                RadButtonDeleteCategory.Visible = true;
            }
        }

        /// <summary>
        /// Creates the category2.
        /// </summary>
        /// <remarks></remarks>
        private void CreateCategory2()
        {
            EvaluationQuestionCategory eqc = (EvaluationQuestionCategory)PlaceHolderCategories.FindControl("EvaluationQuestionCategory" + (categories++).ToString());
            eqc.Visible = true;
            eqc.EnableViewState = true;
        }

        /// <summary>
        /// Loads the categories.
        /// </summary>
        /// <param name="evalID">The eval ID.</param>
        /// <remarks></remarks>
        private void LoadCategories(int evalID)
        {
            BSCEntities context = new BSCEntities();

            List<Evaluation_Category> cats = (from c in context.Evaluation_Category
                                              where c.Evaluation_FK == evalID
                                             // orderby c.ID descending
                                              select c).ToList();
            categories = 0;
            foreach (Evaluation_Category cat in cats)
            {
                EvaluationQuestionCategory eqc = (EvaluationQuestionCategory)PlaceHolderCategories.FindControl("EvaluationQuestionCategory" + (categories++).ToString());
                eqc.CategoryName = cat.Name;
                eqc.IsEditMode = true;
                eqc.Visible = true;

                List<Evaluation_Question> equestions = (from eq in context.Evaluation_Question
                                                        where eq.Evaluation_Category_FK == cat.ID
                                                        
                                                        select eq).ToList();

                eqc.SavedQuestions = equestions;
                eqc.Min = cat.Min;
                eqc.Max = cat.Max;     
            }
        }

        #region CreateEvalution

        /// <summary>
        /// Saves the evaluation.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void SaveEvaluation(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                BSCEntities context = new BSCEntities();

                Evaluation_Period ev = ed.Evalut;

                Evaluation_Period eval = (from evaluation in context.Evaluation_Period
                                          where evaluation.ID == ev.ID
                                          select evaluation).SingleOrDefault();

                if (eval == null)
                {
                    setEvalProperties(ev);

                    context.AddToEvaluation_Period(ev);
                }
                else
                {
                    eval.Name = ed.Evalut.Name;
                    eval.Description = ed.Evalut.Description;
                    eval.StartDate = ed.Evalut.StartDate;
                    eval.EndDate = ed.Evalut.EndDate;
                    setEvalProperties(eval);
                }

                try
                {
                    context.SaveChanges();
                    if (eval != null)
                    {
                        DeleteAllEvaluationObjects(eval.ID);
                    }

                    CreateCategoryQuestions(ev.ID);
                }
                catch (Exception ex)
                {
                    throw new InconsistentDatabaseException("Couldn't save evaluation: " + ex.Message);
                }

                RadButtonCancel.Text = "Back";

                Response.Redirect("EvaluationList.aspx?EvaluationID=" + ev.ID);
            }
        }

        /// <summary>
        /// Sets the eval properties.
        /// </summary>
        /// <param name="ev">The ev.</param>
        /// <remarks></remarks>
        private void setEvalProperties(Evaluation_Period ev)
        {
            ev.Interview = PlaceHolderInterviewPart.Visible;
            ev.PKPIs = PlaceHolderPKPIsPart.Visible;
            ev.Competencies = PlaceHolderCompetenciesPart.Visible;
            ev.Reward = PlaceHolderRewardPart.Visible;

            if (ev.PKPIs == true)
            {
                //pkpi scale
                ev.To1 = (int?)RadNumericTextBoxTo1.Value;
                ev.Verbal1 = RadTextBoxVerbal1.Text;
                ev.From2 = (int?)RadNumericTextBoxFrom2.Value;
                ev.To2 = (int?)RadNumericTextBoxTo2.Value;
                ev.Verbal2 = RadTextBoxVerbal2.Text;
                ev.From3 = (int?)RadNumericTextBoxFrom3.Value;
                ev.To3 = (int?)RadNumericTextBoxTo3.Value;
                ev.Verbal3 = RadTextBoxVerbal3.Text;
                ev.From4 = (int?)RadNumericTextBoxFrom4.Value;
                ev.To4 = (int?)RadNumericTextBoxTo4.Value;
                ev.Verbal4 = RadTextBoxVerbal4.Text;
                ev.From5 = (int?)RadNumericTextBoxFrom5.Value;
                ev.Verbal5 = RadTextBoxVerbal5.Text;
            }
            //revard
            if (ev.Reward == true)
            {
                if (ev.Competencies == true)
                {
                    ev.CompetencyTop = (int?)RadNumericTextBoxCompetencyTop.Value;
                }

                if (ev.PKPIs == true)
                {
                    ev.SigmoidA = BonusSigmoid1.PublicValueA;
                    ev.SigmoidB = BonusSigmoid1.PublicValueB;
                }
                if (ev.Competencies==true && ev.PKPIs==true)
                {
                    ev.BonusSliderValue = BonusSettings1.Value;
                }
                ev.TotalBonus = (decimal)RadNumericTextBoxTotalBonus.Value;
            }
        }

        /// <summary>
        /// Loads the eval properties.
        /// </summary>
        /// <param name="ev">The ev.</param>
        /// <remarks></remarks>
        private void LoadEvalProperties(Evaluation_Period ev)
        {
            if (ev.PKPIs == true)
            {
                //pkpi scale
                RadNumericTextBoxTo1.Value = ev.To1;
                RadTextBoxVerbal1.Text = ev.Verbal1;
                RadNumericTextBoxFrom2.Value = ev.From2;
                RadNumericTextBoxTo2.Value = ev.To2;
                RadTextBoxVerbal2.Text = ev.Verbal2;
                RadNumericTextBoxFrom3.Value = ev.From3;
                RadNumericTextBoxTo3.Value = ev.To3;
                RadTextBoxVerbal3.Text = ev.Verbal3;
                RadNumericTextBoxFrom4.Value = ev.From4;
                RadNumericTextBoxTo4.Value = ev.To4;
                RadTextBoxVerbal4.Text = ev.Verbal4;
                RadNumericTextBoxFrom5.Value = ev.From5;
                RadTextBoxVerbal5.Text = ev.Verbal5;
            }
            if (ev.Reward == true)
            {
                if (ev.Competencies == true)
                {
                    RadNumericTextBoxCompetencyTop.Value = ev.CompetencyTop;
                }
                if (ev.PKPIs == true)
                {
                    BonusSigmoid1.PublicValueA = (double)ev.SigmoidA;
                    BonusSigmoid1.PublicValueB = (double)ev.SigmoidB;
                }
                if (ev.Competencies == true && ev.PKPIs == true)
                {
                    BonusSettings1.Value = (int)ev.BonusSliderValue;
                }
                RadNumericTextBoxTotalBonus.Value = (double)ev.TotalBonus;
            }
        }

        /// <summary>
        /// Deletes all evaluation objects.
        /// </summary>
        /// <param name="eval_ID">The eval_ ID.</param>
        /// <remarks></remarks>
        private void DeleteAllEvaluationObjects(int eval_ID)
        {
            BSCEntities context = new BSCEntities();

            var categories = (from c in context.Evaluation_Category
                              where c.Evaluation_FK == eval_ID
                              select c);
            foreach (Evaluation_Category category in categories)
            {
                context.DeleteObject(category);
            }

            try
            {
                context.SaveChanges();
            }
            catch (Exception e)
            {
                throw new InconsistentDatabaseException("Couldn't save evaluation: " + e.Message);
            }
        }
        
        /// <summary>
        /// Creates the category questions.
        /// </summary>
        /// <param name="evalID">The eval ID.</param>
        /// <remarks></remarks>
        private void CreateCategoryQuestions(int evalID)
        {
            BSCEntities context = new BSCEntities();

            foreach (Control c in PlaceHolderCategories.Controls)
            {
                if (c.GetType().BaseType.Name == "EvaluationQuestionCategory")
                {
                    EvaluationQuestionCategory eqc = (EvaluationQuestionCategory)c;

                    if (eqc.CategoryName == "")
                    {
                        continue;
                    }
                    Evaluation_Category ec = new Evaluation_Category();
                    ec.Evaluation_FK = evalID;
                    ec.Name = eqc.CategoryName;

                    ec.NumberOfQuestions = eqc.NumberQuestions;
                    ec.Min = eqc.Min;
                    ec.Max = eqc.Max;

                    context.AddToEvaluation_Category(ec);
                    try
                    {
                        context.SaveChanges();
                        CreateQuestions(ec.ID, eqc.PublicPanelQuestions);
                    }
                    catch (Exception e)
                    {
                        throw new InconsistentDatabaseException("Couldn't save evaluation: " + e.Message);
                    }
                    
                }
            }
        }

        /// <summary>
        /// Creates the questions.
        /// </summary>
        /// <param name="categoryID">The category ID.</param>
        /// <param name="evaluationQuestions">The evaluation questions.</param>
        /// <remarks></remarks>
        private void CreateQuestions(int categoryID, Panel evaluationQuestions)
        {
            BSCEntities context = new BSCEntities();

            Table t = (Table)evaluationQuestions.FindControl("TableQuestions");
            for (int i = 1; i < t.Rows.Count; ++i)
            {
                Evaluation_Question eq = new Evaluation_Question();
                eq.Question = ((RadTextBox)((t).Rows[i].Cells[0].Controls[0])).Text;
                eq.Evaluation_Category_FK = categoryID;

                context.AddToEvaluation_Question(eq);
            }

            try
            {
                context.SaveChanges();
                
            }
            catch (Exception e)
            {
                throw new InconsistentDatabaseException("Couldn't save evaluation: " + e.Message);
            }
        }

        #endregion

        /// <summary>
        /// Handles the Click event of the RadButtonCancel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void RadButtonCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("ManageEvaluations.aspx");
        }

        /// <summary>
        /// Handles the Click event of the RadButtonDelete control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void RadButtonDelete_Click(object sender, EventArgs e)
        {
            BSCEntities context = new BSCEntities();
            var ep = (from eps in context.Evaluation_Period
                      where eps.ID == ed.Evalut.ID
                      select eps).SingleOrDefault();

            if (ep != null)
            {
                context.DeleteObject(ep);
            }

            try
            {
                context.SaveChanges();

            }
            catch (Exception ex)
            {
                throw new InconsistentDatabaseException("Couldn't delete evaluation: " + ex.Message);
            }

            Response.Redirect("ManageEvaluations.aspx");
        }
    }
}